<template>
	<div class="admin-nav" v-loading="loading">
		<!-- 头部菜单 -->
		<div class="admin-head-nav">
			<div class="head-nav-flex">
				<div class="logo-box">
					<!-- <div class="logo" :style="'background-image:url(' + fileURL + websetting.adminlogoimg + ')'"></div> -->
					<div class="logo" :style="'background-image:url(/images/logo-ico.png)'"></div>
					<div class="title">
						{{ operator.name }}
						<el-tag class="e-m-l-5" v-if="operator.isproprietary" size="mini">自营</el-tag>
						<span class="version">V 7.1.1</span>
						<!-- <div class="money e-p-l-30">账户余额：{{ operator.balance }}</div> -->
					</div>
				</div>
				<!-- <div class="col e-p-r-10">
					<div class="flex align-items-center">
						<el-badge :value="remindCount" slot="reference" :max="99">
							<el-button icon="el-icon-bell" circle size="mini" @click="goRemind"></el-button>
						</el-badge>
					</div>
				</div> -->
				<div class="col">
					<el-menu :default-active="headActiveIndex" mode="horizontal" @select="headHandleSelect">
						<el-submenu index="3">
							<template slot="title">
								<el-avatar style="margin-right: 10px;" :size="26"
									:src="adminInfo.photo == '' ? 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' : fileURL + adminInfo.photo">
								</el-avatar>
								<span>{{ adminInfo.name }}</span>
							</template>
							<!-- <el-menu-item index="myInfo">我的信息</el-menu-item>
							<el-menu-item index="modifyPwd">修改密码</el-menu-item> -->
							<el-menu-item index="logout">退出</el-menu-item>
						</el-submenu>
					</el-menu>
				</div>
			</div>
		</div>
		<div class="admin-content">
			<!-- 左边导航 -->
			<div class="admin-left-nav">
				<el-scrollbar class="text-item" :wrap-class="'text-item-wrap'">
					<el-menu :collapse="isCollapse" :router="true" :default-active="leftActiveIndex"
						@select="leftHandleSelect">
						<template v-for="(item, index) in menu">
							<el-submenu :index="item.active" v-if="item.children">
								<template slot="title">
									<i :class="item.icon" class="e-font-18 e-icon"></i>
									<span>{{ item.title }}</span>
								</template>
								<template v-for="(cell, k) in item.children">
									<el-menu-item v-for="(m, i) in cell.list" :key="m.id" :index="m.path"
										:disabled="m.disabled" v-show="!m.disabled">{{ m.name }}</el-menu-item>
								</template>
							</el-submenu>
							<el-menu-item :index="item.path" :disabled="item.disabled" v-else>
								<i :class="item.icon" class="e-font-18 e-icon"></i>
								<span slot="title">{{ item.title }}</span>
							</el-menu-item>
						</template>
					</el-menu>
					<i class="collapse-btn" :class="isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'"
						@click="isCollapse = !isCollapse"></i>
				</el-scrollbar>
			</div>

			<!-- 主体内容 -->
			<div class="e-flex-1" style="overflow: hidden;">
				<!-- 面包屑导航 -->
				<el-breadcrumb separator="/" class="breadcrumb-box">
					<el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-home"></i>首页</el-breadcrumb-item>
					<el-breadcrumb-item 
						v-for="(item, index) in breadcrumbs" 
						:key="index"
						:to="item.path">
						{{ item.name }}
					</el-breadcrumb-item>
				</el-breadcrumb>
				<!-- 路由切换 -->
				<!-- <el-tabs v-model="activeView" type="card" closable @tab-click="clickTab" @tab-remove="removeTab">
					<el-tab-pane v-for="view in visitedViews" :key="view.path" :name="view.path" :label="view.title">
					</el-tab-pane>
				</el-tabs> -->
				<div class="container-page">
					<el-scrollbar class="text-item" :wrap-class="'text-item-wrap'">
						<nuxt />
					</el-scrollbar>
				</div>
			</div>
		</div>
		<el-dialog title="管理员信息" :visible.sync="dialogVisible" width="800px">
			<el-descriptions :column="2" border :labelStyle="{ width: '130px' }" title="">
				<el-descriptions-item>
					<template slot="label">
						我的名称
					</template>
					{{ my.name }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template slot="label">
						性别
					</template>
					{{ my.sex }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template slot="label">
						手机号码
					</template>
					{{ my.mobile }}
				</el-descriptions-item>

				<el-descriptions-item>
					<template slot="label">
						状态
					</template>
					{{ my.state }}
				</el-descriptions-item>
				<el-descriptions-item>
					<template slot="label">
						头像
					</template>
					<el-image style="width: 100px; height: 100px" :src="fileURL + my.photo"
						:preview-src-list="[fileURL + my.photo]">
						>
					</el-image>
				</el-descriptions-item>
			</el-descriptions>
		</el-dialog>
		<el-dialog title="修改密码" :visible.sync="dialogVisible2" width="600px" :close-on-click-modal="false">
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="当前密码">
					<el-input v-model="form.curPass"></el-input>
				</el-form-item>
				<el-form-item label="新的密码">
					<el-input v-model="form.newPass"></el-input>
				</el-form-item>
				<el-form-item label="确认密码">
					<el-input v-model="form.againPass"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSubmit">确认修改</el-button>
					<el-button @click="dialogVisible2 = false">取消</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
import {
	mapState
} from 'vuex';

export default {
	data() {
		let password = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入密码'));
			} else {
				if (this.form.confirpwd !== '') {
					this.$refs.form.validateField('confirpwd');
				}
				callback();
			}
		};
		let confirpwd = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请再次输入密码'));
			} else if (value !== this.form.password) {
				callback(new Error('两次输入密码不一致!'));
			} else {
				callback();
			}
		};
		return {
			menu: [
				{
					title: '数据中台',
					icon: 'iconfont icon-tongji3',
					active: 't0',
					path: '/datacenter'
				},
				{
					title: '数据总览',
					icon: 'iconfont icon-tongji',
					active: 't8',
					path: '/bigdata/'
					// path:'/overview/'
				},
				{
					title: '加盟商',
					icon: 'iconfont icon-customer',
					active: 't11',
					path:'/franchisee/list',
				},
				{
					title: '客户库',
					icon: 'el-icon-user-solid',
					active: 't1',
					// path: '/user', // 添加父级路径
					children: [
						{
							itemName: '客户库',
							list: [
								{
									name: '客户列表',
									disabled: false,
									path: '/user/list',
									// parentPath: '/user' // 添加父路径关联
								},
								{
									name: '客户组列表',
									disabled: false,
									path: '/enterprise/list',
								},
								{
									name: '客户反馈',
									disabled: false,
									path: '/user/feedback',
								},
							]
						}
					]
				},
				{
					title: '可回收物管理',
					icon: 'el-icon-s-goods',
					active: 't10',
					prem: '',
					children: [
						{
							list: [
								{
									name: '类型设置',
									disabled: false,
									path:'/setting/catalogue',
								},
								{
									name: '可回收物设置',
									disabled: false,
									path:'/setting/productList',
								},
								{
									name: '价格表',
									disabled: false,
									path:'/price/default',
								},
							]
						}
					]
				},
				{
					title: '订单管理',
					icon: 'iconfont icon-order',
					active: 't3',
					children: [
						{
							itemName: '订单管理',
							list: [
								{
									name: '回收订单',
									disabled: false,
									path: '/order/user/list'
								},
								{
									name: '入库订单',
									disabled: false,
									path: '/order/brother/list'
								},
								{
									name: '出库订单',
									disabled: false,
									path: '/order/store/list'
								},
								// {
								// 	name: '移库订单',
								// 	disabled: false,
								// 	path: '/order/move/list'
								// },
								// {
								// 	name: '用户反馈',
								// 	disabled: false,
								// 	path: '/feedback/list'
								// }
							]
						}
					]
				},
				{
					title: '财务管理',
					icon: 'iconfont icon-qian',
					active: 't7',
					children: [
						// {
						// 	itemName: '财务统计',
						// 	list: [
						// 		{
						// 			name: '财务统计',
						// 			disabled: false,
						// 			path: '/finance/statistics'
						// 		}
						// 	]
						// },
						// {
						// 	itemName: '台账查询',
						// 	list: [
						// 		{
						// 			name: '台账查询',
						// 			disabled: false,
						// 			path: '/ledger/brotherOrder'
						// 		},
						// 	]
						// },
						{
							itemName: '提现记录',
							list: [
								{
									name: '提现记录',
									disabled: false,
									path:'/withdrawal/list'
								},
								// {
								// 	name: '提现申请流水',
								// 	disabled: false,
								// 	path:'/finance/withdrawList'
								// }
							]
						},
						{
							itemName: '充值账户设置',
							list: [
								{
									name: '我的账户',
									disabled: false,
									path: '/paymentaccount/list'
								},
							]
						}
					]
				},
				{
					title: '车辆管理',
					icon: 'iconfont icon-maihuo',
					active: 't9',
					children: [
						{
							itemName: '车辆管理',
							list: [
								{
									name: '车辆类型管理',
									disabled: false,
									path:'/vehicle/type'
								},
								{
									name: '车辆管理',
									disabled: false,
									path:'/vehicle/list'
								},
							]
						},
					]
				},
				{
					title: '站点管理',
					icon: 'iconfont icon-shanghuliebiao',
					active: 't5',
					path: '/shop/list',
				},
				{
					title: '管理员',
					icon: 'iconfont icon-jiaosequanxian',
					active: 't13',
					path: '/staff/list',
				},
				{
					title: '系统设置',
					icon: 'iconfont icon-shezhi',
					active: 'm4',
					children: [
						{
							itemName: '系统设置',
							list: [
								{
									name: '基本设置',
									disabled: false,
									path:'/setting/basics'
								},
								{
									name: '小程序banner设置',
									disabled: false,
									path:'/setting/wxbanner'
								},
								{
									name: '小程序看板',
									disabled: false,
									path: '/setting/boardUser'
								},
								{
									name: '佣金设置',
									disabled: false,
									path:'/setting/commission'
								},
								{
									name: '地区库',
									disabled: false,
									path:'/setting/citylist'
								},
							]
						}
					]
				}
			],
			isCollapse: false,
			headActiveIndex: "1",
			leftActiveIndex: "t0",
			topActiveIndex: '',
			dialogVisible: false,
			dialogVisible2: false,
			form: {
				curPass: '',
				newPass: '',
				againPass: ''
			},
			rules: {
				sourcepassword: [{
					required: true,
					message: '请填写当前使用的密码',
					trigger: 'blur'
				}],
				password: [{
					validator: password,
					trigger: 'blur'
				},
				{
					min: 6,
					max: 16,
					message: '长度在 6 到 16 个字符',
					trigger: 'blur'
				}
				],
				confirmpassword: [{
					validator: confirpwd,
					trigger: 'blur'
				},
				{
					min: 6,
					max: 16,
					message: '长度在 6 到 16 个字符',
					trigger: 'blur'
				}
				]
			},
			my: {
				id: 0,
				name: "",
				mobile: "",
				state: "",
				photo: "",
				departmentid: 0,
				departmentname: ""
			},
			remind: {
				pageIndex: 1,
				pageSize: 20
			},
			remindList: []
		}
	},
	watch: {
		theme_color(val) {
			localStorage.setItem('theme_color', val)
		},
		type_Setting(val) {
			localStorage.setItem('type_Setting', val)
		},
		// 新增路由监听
		$route: {
			immediate: true,
			handler(to) {
				this.updateActiveIndex(to.path)
				this.addViewTags()
			}
		}
	},
	created() {
		if (process.client) {
			this.leftActiveIndex = localStorage.getItem('leftActiveIndex') || '/';

			if (localStorage.getItem('theme_color')) {
				this.theme_color = localStorage.getItem('theme_color')
			}
			if (localStorage.getItem('type_Setting')) {
				this.type_Setting = localStorage.getItem('type_Setting')
			}
			if (localStorage.getItem("topActiveIndex")) {
				this.topActiveIndex = localStorage.getItem("topActiveIndex")
			}
			// if (localStorage.getItem("leftActiveIndex")) {
			// 	this.leftActiveIndex = localStorage.getItem("leftActiveIndex")
			// }
			this.$store.dispatch('getUserInfo').then((res) => {
				// console.log('admin.vue-获取用户信息',res)
			})

			this.$axios.get('/Operator/Detail').then((res)=>{
				console.log('运营商详情',res)
				this.$store.commit('setOperator', res)
				// this.operator.name = res.name
			})
		}

		// this.$signalr.start()
		// .then(() => console.log('SignalR 连接已建立'))
		// .catch(err => console.error('SignalR 连接失败:', err));
		// this.$store.dispatch('getUserInfo').then((res) => {
		// 	// console.log('admin.vue-获取用户信息',res)
		// })

		// this.$axios.get('/Operator/Detail').then((res)=>{
		// 	console.log('运营商详情',res)
		// 	this.$store.commit('setOperator', res)
		// 	// this.operator.name = res.name
		// })
	},
	computed: {
		...mapState({
			adminInfo: state => state.userdetail,
			// webSetting: state => state.webSetting,
			remindCount: state => state.remindCount,
			loading: state => state.loading,
			visitedViews: state => state.visitedViews,
			activeView: state => state.activeView,
			operator: state => state.operator
		}),
		// 新增 setter 来处理赋值
		activeView: {
			get() {
				return this.$store.state.activeView
			},
			set(value) {
				this.$store.commit('SET_ACTIVE_VIEW', value)
			}
		},
		breadcrumbs() {
			const crumbs = []
			// 查找当前路由匹配的叶子节点
			const findLeaf = (items) => {
				for (const item of items) {
					if (item.path === this.$route.path) {
						return item
					}
					if (item.children) {
						const found = findLeaf(item.children.flatMap(c => c.list))
						if (found) return { ...item, children: null, ...found }
					}
				}
			}

			// 查找父级菜单
			const leaf = findLeaf(this.menu)
			if (leaf) {
				// 查找父级菜单
				const parent = this.menu.find(m =>
					m.children?.some(c =>
						c.list?.some(i => i.path === leaf.path)
					)
				)

				if (parent) {
					crumbs.push({
						name: parent.title,
						path: parent.path
					})
				}
				crumbs.push({
					name: leaf.name,
					path: leaf.path
				})
			}
			return crumbs
		}
	},
	methods: {
		// 更新激活状态方法
		updateActiveIndex(path) {
			if (process.client) {
				const matchedPath = this.findMenuPath(path)
				if (matchedPath) {
					this.leftActiveIndex = matchedPath
					localStorage.setItem('leftActiveIndex', matchedPath)
				}
			}
		},
		// 递归查找匹配路径
		findMenuPath(path) {
			const search = (menu) => {
				for (const item of menu) {
					if (item.path === path) return item.path
					if (item.children) {
						const found = search(item.children.flatMap(c => c.list))
						if (found) return found
					}
				}
				return null
			}
			return search(this.menu)
		},
		addViewTags() {
			const { name, path, meta } = this.$route
			this.$store.commit('ADD_VISITED_VIEW', {
				name,
				path,
				meta
			})
			this.$store.commit('SET_ACTIVE_VIEW', this.$route || { path: '/' })
		},
		clickTab(tab) {
			this.$router.push(tab.name)
		},
		removeTab(targetName) {
			const views = this.visitedViews
			let activeName = this.activeView

			if (activeName === targetName) {
				views.some((view, index) => {
					if (view.path === targetName) {
						const nextTab = views[index + 1] || views[index - 1]
						activeName = nextTab ? nextTab.path : '/'
						return true
					}
				})
			}

			this.$store.commit('DEL_VISITED_VIEW', { path: targetName })

			// 确保 activeName 有效
			if (!activeName && views.length > 0) {
				activeName = views[0].path
			}

			this.$store.commit('SET_ACTIVE_VIEW', activeName || '/')

			if (activeName !== this.$route.path) {
				this.$router.push(activeName || '/')
			}
		},
		goRemind() {
			this.$router.push({
				path: '/remind/list'
			})
		},
		getReminList() { //获取推送信息列表
			this.$axios.post('/Remind/List', this.remind).then((res) => {
				this.remindList = res.data
			})
		},
		headHandleSelect(key) {
			// console.log(key)
			if (key == 'myInfo') {
				this.getMydata()
				this.dialogVisible = true
			}
			if (key == 'modifyPwd') {
				this.dialogVisible2 = true
			}
			if (key == 'logout') {
				if (process.client) {
					localStorage.removeItem('lifeData')
					localStorage.removeItem('leftActiveIndex')
					localStorage.removeItem('topActiveIndex')
				}
				this.$router.push({
					path: '/login'
				})
			}
		},
		leftHandleSelect(key) {
			if (process.client) {
				this.leftActiveIndex = key
				localStorage.setItem('leftActiveIndex', key)
				// 如果已经是当前路由则不重复跳转
				if (this.$route.path !== key) {
					this.$router.push(key)
				}
			}
		},
		getMydata() {
			this.$store.dispatch('getUserInfo').then((res) => {
				this.my = res
			})
		},
		onSubmit() {
			this.$refs.form.validate((valid) => {
				if (valid) {
					this.$axios.post('/User/Account/FindPassword', this.form).then((res) => {
						this.$alert('密码修改成功, 请重新登录！', '提示', {
							confirmButtonText: '确定',
							showClose: false,
							callback: action => {
								if (process.client) {
									localStorage.removeItem('lifeData')
								}
								this.$router.push({
									path: '/login'
								})
							}
						});
					})
				} else {
					return false;
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.el-tabs {
	background: #fff;
	padding: 0 20px;

	::v-deep .el-tabs__header {
		margin: 0;

		.el-tabs__nav-wrap::after {
			height: 1px;
		}

		.el-tabs__item {
			height: 40px;
			line-height: 40px;

			&.is-active {
				background: var(--main);
				color: #fff;
				border-bottom-color: var(--main);
			}
		}
	}
}

.breadcrumb-box {
	padding: 15px 20px;
	background: #fff;
	border-bottom: 1px solid #ebeef5;
	margin-bottom: 1px;
}

.admin-nav {
	.admin-head-nav {
		.head-nav-flex {
			display: flex;
			border-bottom: solid 1px #e6e6e6;
			background-color: #fff;

			.el-menu {
				border-bottom: 0;
				display: flex;
				justify-content: flex-end;
			}

			.col {
				display: flex;
				padding-left: 15px;
			}

			.logo-box {
				display: flex;
				flex: 1;

				.logo {
					background-repeat: no-repeat;
					background-position: center;
					background-size: 80%;
					// background-color: #fff;
					width: 60px;
					height: 60px;
					box-sizing: border-box;
				}

				.title {
					display: flex;
					// height: 60px;
					align-items: center;
					padding: 0 50px 0 5px;
					font-size: 18px;
				}

				.version {
					font-size: 12px;
					color: var(--grey);
					padding-left: 10px;
				}
			}

			.icon-nemu {
				display: flex;
				align-items: center;

				.iconfont {
					font-size: 22px;
					margin-left: 30px;
					cursor: pointer;
				}
			}

			.col-auto {
				flex: 1;
			}
		}
	}

	.admin-content {
		display: flex;

		.admin-left-nav {
			background-color: #fff;
			border-right: solid 1px #e6e6e6;
			box-shadow: 0 0 16px 0 rgba(0, 0, 0, .04);
			// width: 220px;

			.el-menu {
				width: 220px;
				border-right: 0;
			}

			.collapse-btn {
				cursor: pointer;
				padding: 5px;
				background-color: var(--light);
				position: absolute;
				bottom: 10px;
				right: 18px;

				&:hover {
					background-color: var(--blue);
					color: #fff;
				}
			}

			.text-item {
				height: calc(100vh - 61px);

				::v-deep {
					.text-item-wrap {
						overflow-x: hidden;
					}
				}
			}

			.left-nav-title {
				line-height: 50px;
				padding: 0 15px;
				font-size: 16px;
				position: relative;
				border-bottom: 1px solid var(--light);
				width: 160px;
			}

			.left-nav-sub-title {
				font-weight: bold;
				color: #000;
				font-size: 14px;
				display: block;
				border-bottom: 1px solid var(--light);
				padding-bottom: 10px;
				margin-right: 20px;
			}

			.el-menu-item-group {
				margin-bottom: 15px;
			}

			.el-menu-vertical {
				border-right: 0;
			}

			.admin-left-head-nav {
				display: flex;
				flex-direction: column;

				.el-menu-item {
					text-align: center
				}
			}

			.e-icon {
				display: inline-block;
				width: 25px;
			}
		}

		.container-page {
			// flex: 1;
			// min-width: 800px;

			.text-item {
				height: calc(100vh - 135px);
				border-radius: 5px;

				::v-deep {
					.text-item-wrap {
						overflow-x: hidden !important;
					}
				}
			}
		}
	}

	.el-menu-vertical {
		.el-menu-item {
			font-size: 14px;
			line-height: 48px;
			height: 48px;
		}
	}

	.el-menu--collapse {
		width: 64px !important;
		text-align: center;
		height: calc(100vh - 100px);
		border-right: 0;

		.el-menu-item>div {
			padding: 0 13px !important;
		}
	}
}

.el-submenu.is-active.is-opened {
	.el-submenu__title {
		color: var(--main);

		.iconfont {
			color: var(--main);
		}

		.el-submenu__icon-arrow {
			color: var(--main);
		}
	}
}

// 待办事项
.todo-list {
	.item {
		display: flex;
		border-bottom: 1px solid var(--border-light);
		padding: 15px 0;

		&:last-child {
			border-bottom: 0;
		}

		.icon {
			width: 40px;
			height: 40px;
			color: #fff;
			background-color: var(--orange);
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 3px;
			margin-right: 10px;

			&.t1 {
				background-color: var(--orange)
			}

			&.t2 {
				background-color: var(--green)
			}

			&.t3 {
				background-color: var(--cyan)
			}

			&.t4 {
				background-color: var(--primary)
			}
		}

		.item-content {
			.tname {
				font-size: 14px;
			}

			.text {
				font-size: 14px;
				color: var(--dark);
				padding: 3px 0;
			}

			.date {
				font-size: 12px;
				color: var(--grey);
			}
		}
	}
}
</style>